package cn.kgc.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤登录请求
 *
 * Filter生命周期
 *
 * @author: mosin
 * @version: v1.0  2022/3/21
 */
/*
   @WebFilter    /  过滤静态资源的请求    /*    .jsp的请求也会被过滤
 */
//@WebFilter("/*")
public class LoginFilter implements Filter {

     // 服务器启动则会创建该对象
    public  LoginFilter(){
        System.out.println("登录过滤器对象被创建!");
    }

    // 过滤器对象创建完成调用一次 init方法
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init()");
    }

    //请求一次执行一次 过滤
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter()");

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;

        //统一设置编码格式
        req.setCharacterEncoding("utf-8");

        //判定是否登录  用户登录放行   否则重定向到登录页
        HttpSession session = req.getSession();
        //获取session中存储的用用户名
        String username =(String) session.getAttribute("username");
        System.out.println("username = " + username);

        String requestURI = req.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        //放行特定的页面  login.jsp   特定的静态资源 .css .js    特定的请求  登录 login   注册 register
        if(requestURI.endsWith("login.jsp")||requestURI.endsWith(".css")||requestURI.endsWith("login")){
            System.out.println("请求放行前");
            //放行请求
            filterChain.doFilter(req,resp);

            System.out.println("请求完成后，响应");
        }else{
            if(username==null){//没有登录  重定向到登录页
                resp.sendRedirect("/login.jsp");
            }else{
                //放行请求
                filterChain.doFilter(req,resp);
            }
        }
    }

    /**
     * 服务器停止时  调用该方法
     */
    @Override
    public void destroy() {
        System.out.println("destroy()");
    }
}
